package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }
    @Override
    public PageResult<AddressBookResDTO> page(AddressBookPageQueryReqDTO dto) {
        Long userId = UserContext.currentUserId();
        IPage page = new Page(dto.getPageNo(),dto.getPageSize());
        LambdaQueryWrapper<AddressBook> wrapper = Wrappers.<AddressBook>lambdaQuery().eq(AddressBook::getUserId, userId).orderBy(StringUtils.isNotBlank(dto.getOrderBy1()), dto.getIsAsc1(), AddressBook::getIsDefault)
                .orderBy(StringUtils.isNotBlank(dto.getOrderBy2()), dto.getIsAsc2(), AddressBook::getUpdateTime);
        baseMapper.selectPage(page,wrapper);
        PageResult<AddressBookResDTO> result = new PageResult<>();
        result.setPages(page.getPages());
        result.setTotal(page.getTotal());
        result.setList(page.getRecords());
        return result;
    }
    @Override
    public void addAddressBook(AddressBookUpsertReqDTO dto) {
        Long userId = UserContext.currentUserId();
        if(userId==null){
            throw new ForbiddenOperationException("用户未登录");
        }
        AddressBook addressBook = BeanUtils.copyBean(dto, AddressBook.class);
        addressBook.setUserId(userId);
        String location = dto.getLocation();
        String[] split = location.split(",");
        addressBook.setLat(Double.valueOf(split[0]));
        addressBook.setLon(Double.valueOf(split[1]));
        if(dto.getIsDefault()==1){
            AddressBook addressBook1 = lambdaQuery().eq(AddressBook::getUserId, userId).eq(AddressBook::getIsDefault, 1).one();
            if(addressBook1!=null){
                lambdaUpdate().set(AddressBook::getIsDefault, 0).eq(AddressBook::getId, addressBook1.getId()).update();
            }
        }
        this.save(addressBook);
    }


    @Override
    public void updateAddress(AddressBookUpsertReqDTO dto, Long id) {
        AddressBook addressBook = this.getById(id);
        if(addressBook==null){
            throw new ForbiddenOperationException("地址不存在");
        }
        Double lat=null;
        Double lon=null;
        if(dto.getLocation()!=null){
            String[] split = dto.getLocation().split(",");
            lat= Double.valueOf(split[0]);
            lon=Double.valueOf(split[1]);
        }
        boolean update = this.lambdaUpdate()
                .set(StringUtils.isNotBlank(dto.getAddress()), AddressBook::getAddress, dto.getAddress())
                .set(StringUtils.isNotBlank(dto.getCity()), AddressBook::getCity, dto.getCity())
                .set(StringUtils.isNotBlank(dto.getCounty()), AddressBook::getCounty, dto.getCounty())
                .set(StringUtils.isNotBlank(dto.getLocation()), AddressBook::getLat, lat)
                .set(StringUtils.isNotBlank(dto.getLocation()), AddressBook::getLon, lon)
                .set(StringUtils.isNotBlank(dto.getName()), AddressBook::getName, dto.getName())
                .set(StringUtils.isNotBlank(dto.getPhone()), AddressBook::getPhone, dto.getPhone())
                .set(StringUtils.isNotBlank(dto.getProvince()), AddressBook::getProvince, dto.getProvince())
                .set(dto.getIsDefault() != null, AddressBook::getIsDefault, dto.getIsDefault())
                .eq(AddressBook::getId, id).update();
        if(!update){
            throw new DBException("修改地址失败");
        }

    }

    @Override
    public void deleteBatch(List<String> ids) {
        List<Long> deleteIds=new ArrayList<>();
        if(ids!=null&&ids.size()>0){
            for (String id : ids) {
                deleteIds.add(Long.valueOf(id));
            }
            this.removeByIds(deleteIds);
        }else{
            throw new ForbiddenOperationException("没有删除数据");
        }
    }
    @Override
    public AddressBook getdefaultAddress() {
        Long userId = UserContext.currentUserId();
        AddressBook addressBook = lambdaQuery().eq(AddressBook::getUserId, userId).eq(AddressBook::getIsDefault, CertificationStatusEnum.PROGRESSING).one();
        return addressBook;
    }
    @Override
    public void setDefault(Long id, Integer flag) {
        AddressBook addressBook = this.getById(id);
        Long userId = UserContext.currentUserId();
        if(addressBook==null){
            throw new ForbiddenOperationException("地址不存在");
        }
        if(flag==1){
            AddressBook addressBook1 = lambdaQuery().eq(AddressBook::getUserId, userId).eq(AddressBook::getIsDefault, CertificationStatusEnum.PROGRESSING).one();
            if(addressBook1!=null){
                lambdaUpdate().set(AddressBook::getIsDefault, 0).eq(AddressBook::getId, addressBook1.getId()).update();
            }
        }
        boolean update = lambdaUpdate().set(AddressBook::getIsDefault, flag).eq(AddressBook::getId, id).update();
        if(!update){
            throw new DBException("修改失败");
        }
    }


}

